/* eslint-env browser */

import * as Y from 'yjs';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { QuillBinding } from 'y-quill';
import Quill from 'quill';
import QuillCursors from 'quill-cursors';

Quill.register('modules/cursors', QuillCursors);
const roomname = `codemirror-demo-${new Date().toLocaleDateString('en-CA')}`;

window.addEventListener('load', () => {
  const ydoc = new Y.Doc();
  // 使用 HocuspocusProvider 连接 Hocuspocus 服务器
  const provider = new HocuspocusProvider({
    url: 'ws://localhost:1234', // Hocuspocus 服务器地址
    name: roomname,
    document: ydoc
  });
  const ytext = ydoc.getText('quill');
  const editorContainer = document.createElement('div');
  editorContainer.setAttribute('id', 'editor');
  document.body.insertBefore(editorContainer, null);

  const editor = new Quill(editorContainer, {
    modules: {
      cursors: true,
      toolbar: [
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        ['image', 'code-block']
      ],
      history: {
        userOnly: true
      }
    },
    placeholder: 'Start collaborating...',
    theme: 'snow' // or 'bubble'
  });

  const binding = new QuillBinding(ytext, editor, provider.awareness);

  ytext.observe(() => {
    console.log('Yjs 文档内容更新:', ytext.toString());
  });
  const connectBtn = document.getElementById('y-connect-btn');
  connectBtn.addEventListener('click', () => {
    if (provider.shouldConnect) {
      provider.disconnect();
      connectBtn.textContent = 'Connect';
    } else {
      provider.connect();
      connectBtn.textContent = 'Disconnect';
    }
  });

  window.example = { provider, ydoc, ytext, binding, Y };
});